package com.htthorizon.ws.webservice.service.impl;


import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.htthorizon.common.core.domain.R;
import com.htthorizon.system.api.RemoteUserService;
import com.htthorizon.system.api.domain.MonitorAll;

import com.htthorizon.ws.webservice.getKpiValue.ApiDTO;
import com.htthorizon.ws.webservice.getKpiValue.ApiResponse;
import com.htthorizon.ws.webservice.getKpiValue.RequestInfo;
import com.htthorizon.ws.webservice.getKpiValue.Result;
import com.htthorizon.ws.webservice.service.GetKPIValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@WebService(targetNamespace = "http://service.webservice.ws.htthorizon.com/")
public class GetKPIValueServiceImpl implements GetKPIValueService {

    private static int riseNum = 0;

    @Autowired
    private   RemoteUserService remoteUserService;



    @WebMethod
    @WebResult(name = "return")
    @Override
    public String getKPIValue(@WebParam(name = "param") String param) {
        System.out.println("ws");
        long start1 = System.currentTimeMillis();
        System.out.println("开始时间："+ DateUtil.date());

        R<MonitorAll> all = remoteUserService.all();
        MonitorAll monitorAll1 = new MonitorAll();
        MonitorAll monitorAll = Optional.ofNullable(all).map(R::getData).orElse(new MonitorAll());


        //获取参数信息
        JAXBContext jaxbContext;
        RequestInfo requestInfo = null;
        String xmlString = null;

        LocalDate currentDate = LocalDate.now(); // 当前日期

        // 创建 Calendar 对象并获取当前时间
        Calendar calendar = Calendar.getInstance();

        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

        // 格式化当前日期为字符串
        String formattedDate = currentDate.format(formatter);

        // 获取当前分钟数
        int minute = calendar.get(Calendar.MINUTE);
        if ("2023-08".equals(formattedDate)) {
            if (minute % 5 == 0) {
                riseNum += 2;
                if (riseNum == 20) {
                    riseNum = 0;
                }
            }
        }

        try {
            jaxbContext = JAXBContext.newInstance(RequestInfo.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            System.out.println("param"+param);
//            param="<?xml version=\"1.0\" encoding=\"gb2312\"?>\n\" +\n" +
//                    "                    \"<info>\\n\" +\n" +
//                    "                    \"<CorporationCode>16</CorporationCode>\n\" +\n" +
//                    "                    \"<!--传入的指标名称可以为一个或多个,BusinessSystemLoginRoll和BusinessSystemOnlineRoll只能单独调用-->\n\" +\n" +
//                    "                    \"<Time>\" + \"\" + \"</Time>\n\" +\n" +
//                    "                    \"<api name=\"BusinessUserRegNum\"></api>\n\" +\n" +
//                    "                    \"<api name=\"BusinessDataTableSpace\"></api>\n\" +\n" +
//                    "\n" +
//                    "                    \"<api name=\"BusinessSystemOnlineNum\"></api>\n\" +\n" +
//                    "                    \"<api name=\"BusinessDayLoginNum\"></api>\n\" +\n" +
//                    "                    \"<api name=\"BusinessVisitCount\"></api>\n\" +\n" +
//                    "                    \"<api name=\"BusinessSystemSessionNum\"></api>\n\" +\n" +
//                    "                    \"<api name=\"BusinessSystemResponseTime\"></api>\n\" +\n" +
//                    "                    \"<api name=\"BusinessSystemRunningTime\"></api>\n\" +\n" +
//                    "                    \"<api name=\"BusinessSystemDBTime\"></api>\n\" +\n" +
//                    "                    \"</info>";
            param = param.replaceAll("(?m)^\\s*$[\n\r]{1,}", "");
            StringReader reader = new StringReader(param.trim());
            requestInfo = (RequestInfo) unmarshaller.unmarshal(reader);

            Result result = new Result();
            result.setStatus("success");
            result.setMessage("调用接口成功！");

            List<ApiResponse> apiResponseList = Lists.newArrayList();

            Random random = new Random();
            for (ApiDTO apiDTO : requestInfo.getApi()) {
                // 增加服务端的业务处理逻辑
                if ("BusinessUserRegNum".equals(apiDTO.getName())) {
                    // 注册用户数（单位：个）
                    ApiResponse api1 = new ApiResponse();
                    api1.setName("BusinessUserRegNum");
                    int i = monitorAll.getBusinessUserRegNum();
                    api1.setValue(String.valueOf(i));
                    apiResponseList.add(api1);
                } else if ("BusinessSystemOnlineNum".equals(apiDTO.getName())) {
                    // 在线用户数（单位：个）
                    ApiResponse api1 = new ApiResponse();
                    api1.setName("BusinessSystemOnlineNum");
                    int i = monitorAll.getBusinessSystemOnlineNum();
                    api1.setValue(String.valueOf(i));
                    apiResponseList.add(api1);
                } else if ("BusinessDayLoginNum".equals(apiDTO.getName())) {
                    // 日登录人数（单位：个）
                    ApiResponse api1 = new ApiResponse();
                    api1.setName("BusinessDayLoginNum");
                    int i =monitorAll.getBusinessDayLoginNum();
                    api1.setValue(String.valueOf(i));
                    apiResponseList.add(api1);
                } else if ("BusinessVisitCount".equals(apiDTO.getName())) {
                    // 累计访问人次（单位：人次）
                    ApiResponse api1 = new ApiResponse();
                    api1.setName("BusinessVisitCount");
                    int i = monitorAll.getBusinessVisitCount();
                    api1.setValue(String.valueOf(i));
                    apiResponseList.add(api1);
                } else if ("BusinessSystemSessionNum".equals(apiDTO.getName())) {
                    // 页面会话连接数（单位：个）注：在线用户数基础上+随机数
                    ApiResponse api1 = new ApiResponse();
                    api1.setName("BusinessSystemSessionNum");
                    int i = monitorAll.getBusinessSystemSessionNum();
                    api1.setValue(String.valueOf(i));
                    apiResponseList.add(api1);
                } else if ("BusinessSystemResponseTime".equals(apiDTO.getName())) {
                    // 系统服务响应时长(单位:毫秒)
                    ApiResponse api1 = new ApiResponse();
                    api1.setName("BusinessSystemResponseTime");
                    Double i = monitorAll.getBusinessSystemResponseTime().doubleValue();
                    api1.setValue(String.valueOf(i));
                    apiResponseList.add(api1);
                } else if ("BusinessSystemRunningTime".equals(apiDTO.getName())) {
                    // 系统健康运行时长（单位：秒）
                    ApiResponse api1 = new ApiResponse();
                    api1.setName("BusinessSystemRunningTime");
                    Instant start = Instant.now();
                    RuntimeMXBean runtimeMX = ManagementFactory.getRuntimeMXBean();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date startTime = new Date(runtimeMX.getStartTime());
                    System.out.println("系统启动时间"+dateFormat.format(startTime));
                    Date nowTime=new Date();
                    System.out.println("当前系统时间"+dateFormat.format(nowTime));
                    long diff = nowTime.getTime() - startTime.getTime();
                    long theMinutes  = diff /1000;
                    Instant end = Instant.now();
                    long timeElapsed = Duration.between(start, end).toMillis()/1000;
                    //单位为秒
                    long sec =theMinutes+timeElapsed;
                    api1.setValue(String.valueOf(sec));
                    apiResponseList.add(api1);
                } else if ("BusinessDataTableSpace".equals(apiDTO.getName())) {
                    // 业务应用系统占用表空间大小（单位：MB）
                    ApiResponse api1 = new ApiResponse();
                    api1.setName("BusinessDataTableSpace");
                    String aDouble = monitorAll.getBusinessDataTableSpace().toString();
                    api1.setValue(aDouble);
                    apiResponseList.add(api1);
                } else if ("BusinessSystemDBTime".equals(apiDTO.getName())) {
                    // 数据库平均响应时长（单位：毫秒）
                    ApiResponse api1 = new ApiResponse();
                    api1.setName("BusinessSystemDBTime");
                    Double doublue = monitorAll.getBusinessSystemDBTime().doubleValue();
                    api1.setValue(String.valueOf(doublue));
                    apiResponseList.add(api1);
                }
            }
            result.setApis(apiResponseList);

            JAXBContext jaxbContextResult = JAXBContext.newInstance(Result.class);
            Marshaller marshaller = jaxbContextResult.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

            StringWriter writer = new StringWriter();
            marshaller.marshal(result, writer);
            xmlString = "<?xml version=\"1.0\" encoding=\"gb2312\"?>\n" + writer.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        //解析参数信息并统计指标值
        //将统计结果封装成要求的格式
        //返回结果给采集端

        System.out.println(xmlString);
        System.out.println("结束时间时间："+ DateUtil.date());
        long end = System.currentTimeMillis();
        System.out.println("耗时:"+(end-start1)+"ms");

        return xmlString;
    }



    @Override
    public String test(String name) {
        return "hello"+name;
    }

}
